import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import './RadioButtonList.sass';

export default class RadioButtonList extends Component {
  static propTypes = {
    name: PropTypes.string,
    options: PropTypes.array,
    value: PropTypes.any,
    defaultValue: PropTypes.any,
    theme: PropTypes.string,
    disabled: PropTypes.bool,
    onChange: PropTypes.func
  };

  static defaultProps = {
    disabled: false,
    theme: 'default'
  };

  state = {value: this.props.value != undefined ? this.props.value : this.props.defaultValue};

  checkChange = (value) => {
    return (event) => {
      if (event.target.checked) {
        this.setState({value});
        if (this.props.onChange) {
          this.props.onChange(value);
        }
      }
    };
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.value) {
      this.setState({value: nextProps.value});
    }
  }

  get value() {
    return this.state.value;
  }

  set value(val) {
    this.setState({value: val});
  }

  render() {
    const {
      name,
      options,
      value,
      defaultValue,
      theme,
      disabled,
      onChange,
      ...other
    } = this.props;

    let createRadioButton = (option, i) => {
      let {label, value} = typeof(option) == 'string' ? {label: option, value: option} : option;
      let checked = value === this.state.value;
      return (
        <label key={i} className={classnames({disabled, checked})}>
         <input type="radio" name={name} disabled={disabled} checked={checked} onChange={this.checkChange(value)} />
         {label}
        </label>
      );
    };

    return (
      <div className={`radio-group theme-${theme}`} {...other}>
        {options.map(createRadioButton)}
      </div>
    );
  }
}
